package com.huluobo.a2109mvpimdemo.conversation;


import android.util.Log;

import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;


import com.huluobo.a2109mvpimdemo.R;
import com.huluobo.a2109mvpimdemo.adapter.ConversationAdapter;
import com.huluobo.a2109mvpimdemo.base.BaseFragment;
import com.hyphenate.EMMessageListener;
import com.hyphenate.chat.EMClient;
import com.hyphenate.chat.EMConversation;
import com.hyphenate.chat.EMMessage;

import java.util.ArrayList;
import java.util.List;

public class MyConversationFragment extends
        BaseFragment<ConversationContract.View, ConversationPresenter> implements ConversationContract.View {

    private RecyclerView recyclerView;
    private ConversationAdapter conversationAdapter;
    private List<EMConversation> conversations = new ArrayList<>();

    private EMMessageListener messageListener = new EMMessageListener() {
        @Override
        public void onMessageReceived(List<EMMessage> messages) {
            presenter.loadConversations();
        }
    };


    @Override
    protected int bindingLayoutId() {
        return R.layout.fragment_my_conversation;
    }

    @Override
    protected void initData() {
        presenter = new ConversationPresenter();
        EMClient.getInstance().chatManager().addMessageListener(messageListener);
    }

    @Override
    protected void loadData() {
        super.loadData();
        presenter.loadConversations();
    }

    @Override
    protected void initView() {
        recyclerView = findViewById(R.id.conversation_rv);
        recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
        conversationAdapter = new ConversationAdapter(conversations, getContext());
        recyclerView.setAdapter(conversationAdapter);


    }

    @Override
    public void loadConversationsSuccess(List<EMConversation> conversations) {
        getActivity().runOnUiThread(new Runnable() {
            @Override
            public void run() {
                MyConversationFragment.this.conversations.clear();
                MyConversationFragment.this.conversations.addAll(conversations);
                conversationAdapter.notifyDataSetChanged();
            }
        });
    }

    @Override
    public void onResume() {
        super.onResume();
        presenter.loadConversations();
    }

    @Override
    public void loadConversationsFailed(String error) {
        Log.i("TagA", "error:" + error);
    }
}